1. C++ / Говнокод #12789

    +13

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    CompoundExpression*
    CompoundExpression::newBinaryExpression(
    	BasicBinaryOperation::Type operation,
    	const Expression *x,
    	const Expression *y
    ) {
    	vector<Expression::const_pointer> params(2);
    	params[0] = x;
    	params[1] = y;
    	
    	// integer power optimization
    	if (operation == BasicBinaryOperation::POWER) {
    		if (y->isNumber()) {
    			Number::const_pointer number_y = dynamic_cast<typeof number_y>(y);
    			if (number_y != NULL && number_y->isIntegerNumber()) {
    				IntegerNumber::const_pointer integer_y = dynamic_cast<typeof integer_y>(number_y);
    				if (integer_y != NULL) {
    					operation = BasicBinaryOperation::INT_POWER;
    					return new CompoundExpression(BinaryOperation::getOperation(operation), params);
    				}
    			}
    		}
    	}
    	
    	// x^(y/n), where 'n' is odd integer
    	// transform to '(x^y)^(1/n)'
    	if (operation == BasicBinaryOperation::POWER) {
    		if (y->isCompoundExpression()) {
    			auto compoundExpressionY = dynamic_cast<CompoundExpression::const_pointer>(y);
    			if (compoundExpressionY != NULL && compoundExpressionY->operation->isBinary()) {
    				auto innerOperation = compoundExpressionY->operation;
    				auto binaryOperation = dynamic_cast<BinaryOperation const *>(innerOperation);
    				if (binaryOperation != NULL && binaryOperation->getType() == BasicBinaryOperation::DIVIDE) {
    					Expression::const_pointer   numerator = compoundExpressionY->params[0];
    					Expression::const_pointer denominator = compoundExpressionY->params[1];
    					if (denominator->isNumber()) {
    						auto numberDenominator = dynamic_cast<Number::const_pointer>(denominator);
    						if (numberDenominator != NULL && numberDenominator->isIntegerNumber()) {
    							auto integerDenominator = dynamic_cast<IntegerNumber::const_pointer>(numberDenominator);
    							if (integerDenominator != NULL && (integerDenominator->intValue() % 2) != 0) {
    								auto base = CompoundExpression::newBinaryExpression(BasicBinaryOperation::POWER, x, numerator);
    								return CompoundExpression::newBinaryExpression(BasicBinaryOperation::NTH_ROOT, integerDenominator, base);
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    
    	return new CompoundExpression(BinaryOperation::getOperation(operation), params);
    }

    Моё. Потребовалось воткнуть оптимизацию арифметического выражения некоторого вида. В результате родился вот такой костыль.

    UncleAli, 24 Марта 2013

    Комментарии (4)
  2. C++ / Говнокод #12770

    +19

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    struct BufInfo 
    {
    	const tbal::Bitmap &src, &dst;
    	int y1, y2;
    	BufInfo (const tbal::Bitmap &scr, const tbal::Bitmap &dst, int y1, int y2) : src(src), dst(dst), y1(y1), y2(y2) {}
    };

    Как можно проебать час жизни...

    TarasB, 20 Марта 2013

    Комментарии (51)
  3. C++ / Говнокод #12769

    +14

    1. 1
    2. 2
    3. 3
    4. 4
    template<typename T>
    constexpr size_t printed_sizeof() {
        return log10(sizeof(T)) + 1;
    }

    Осваиваем новые стандарты.

    roman-kashitsyn, 19 Марта 2013

    Комментарии (18)
  4. C++ / Говнокод #12768

    +20

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    #define STR(a) #a
    
    #define EXCEPTION_CLASS_CREATE(a)                   \
    class a : public std::exception                     \
    {                                                   \
    public:                                             \
        a()                                             \
        {                                               \
            d(STR(a)"\n");                              \
        }                                               \
                                                        \
        a(const char * format, ...)                     \
        {                                               \
            char buffer[ 1024 ];                        \
            va_list vl;                                 \
            va_start( vl, format );                     \
            vsnprintf( buffer, sizeof(buffer), format, vl ); \
            va_end( vl );                               \
            _str.append( buffer );                      \
            d(STR(a)" %s\n", buffer);                   \
        }                                               \
                                                        \
        ~a() throw()                                    \
        {                                               \
        }                                               \
                                                        \
        const char* what() const throw()                \
        {                                               \
            return _str.c_str();                        \
        }                                               \
    private:                                            \
        std::string _str;                               \
    };
    // ...
    EXCEPTION_CLASS_CREATE( InternalException )

    Мы очень любим varargs

    roman-kashitsyn, 19 Марта 2013

    Комментарии (13)
  5. C++ / Говнокод #12765

    +13

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    class session {
    public:
        session(int id, boost::asio::io_service &io_service) :
            id(id),
            timer(io_service)
        {
            timer.expires_from_now(session_timeout);
            timer.async_wait(boost::bind(&session::on_timeout, this, _1));
        }
    
        void on_timeout(const boost::system::error_code &error) {
            if (error)
                return;
            std::cout << "Session timed out " << id << std::endl;
        }
    
    private:
        int id;
        boost::asio::deadline_timer timer;
    };
    
    std::map<boost::asio::ip::udp::endpoint, boost::shared_pointer<session> > sessions;

    sessions.erase(endpoint) приводит к небольшому насилию над трупом сессии... Ничего конечно не вылетает, и никогда не сломается, но совесть мучает, неприятно пользоваться UB'ом.

    bormand, 18 Марта 2013

    Комментарии (45)
  6. C++ / Говнокод #12756

    +15

    1. 1
    2. 2
    3. 3
    String testName;
    //...
    std::swap(testName,  _testName);

    String из thirdparty-библиотеки, а swap везде в нашем коде. По очевидным причинам получаем подение производительности.

    LispGovno, 16 Марта 2013

    Комментарии (41)
  7. C++ / Говнокод #12746

    +23

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    struct mystream: public std::ostream 
    {
        mystream(std::ostream & o): std::ostream(o.rdbuf()) {}
    
        template <class T>
        mystream & operator << (T const & arg)
        {
            if (enabled_) as_std_ostream() << arg;
            return *this;
        }
    
        // дерьмо STX
        mystream & operator << (std::ostream & (*f)(std::ostream &))
        {
            if (enabled_) as_std_ostream() << f;
            return *this;
        }
    
        mystream & operator << (std::ios & (*f)(std::ios &))
        {
            if (enabled_) as_std_ostream() << f;
            return *this;    
        }
    
        mystream & operator << (std::ios_base & (*f)(std::ios_base &))
        {
            if (enabled_) as_std_ostream() << f;
            return *this;
        }
        // дерьмо ETX
    
        void enable() { enabled_ = true; }
        void disable() { enabled_ = false; }
    
    protected:
        bool enabled_;
        std::ostream & as_std_ostream() { return *this; }
    };

    а так хотелось хоть сегодня рыбки поесть захерачить вместо трёх перегрузок
    template <class O>
    mystream & operator << (O & (*f)(O &)) { ...

    defecate-plusplus, 13 Марта 2013

    Комментарии (34)
  8. C++ / Говнокод #12736

    +28

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    class atoi_func
    {
    public:
        atoi_func(): value_() {}
    
        inline int value() const { return value_; }
    
        inline bool operator() (const char *str, size_t len)
        {
            value_ = 0;
            int sign = 1;
            if (str[0] == '-') { // handle negative
                sign = -1;
                ++str;
                --len;
            }
    
            switch (len) { // handle up to 10 digits, assume we're 32-bit
                case 10:    value_ += (str[len-10] - '0') * 1000000000;
                case  9:    value_ += (str[len- 9] - '0') * 100000000;
                case  8:    value_ += (str[len- 8] - '0') * 10000000;
                case  7:    value_ += (str[len- 7] - '0') * 1000000;
                case  6:    value_ += (str[len- 6] - '0') * 100000;
                case  5:    value_ += (str[len- 5] - '0') * 10000;
                case  4:    value_ += (str[len- 4] - '0') * 1000;
                case  3:    value_ += (str[len- 3] - '0') * 100;
                case  2:    value_ += (str[len- 2] - '0') * 10;
                case  1:    value_ += (str[len- 1] - '0');
                    value_ *= sign;
                    return value_ > 0;
                default:
                    return false;
            }
        }
    private:
        int value_;
    };

    standard atoi()
    79142 milliseconds

    class atoi_func
    131 milliseconds.

    Если приходится велосипедить стандартные функции, то это камень в огород С++. Видать кресты писали гении ассемблерной оптимизации.

    LispGovno, 13 Марта 2013

    Комментарии (20)
  9. C++ / Говнокод #12733

    +14

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    void ThumbnailAdapter::clearCache(size_t index) {
        if ((size_t)-1 == index) {
            mImages.clear();
        } else {
            ImagesMap::iterator it = mImages.find (index);
            if (mImages.end() != it) {
                mImages.erase(it);
            }
        }
    }

    годная очистка map'ы

    shomeser, 12 Марта 2013

    Комментарии (26)
  10. C++ / Говнокод #12716

    +16

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    class Context;
    
    class AbstractState
    {
    	Context * m_context;
    
    protected:
    	Context * context() const { return m_context; }
    
    public:
    	AbstractState(Context * context) : m_context(context) { };
    	virtual ~AbstractState() { }
    	virtual void doSomething() = 0;
    };
    
    class Context
    {
    	std::unique_ptr<AbstractState> m_state;
    
    public:
    	enum State
    	{
    		State1,
    		State2,
    	};
    	Context() { switchToState(State1); }
    	void switchToState(State newState);
    	void doSomething() { m_state->doSomething(); }
    	void someCleanup() { }
    };
    
    class ConcreteState1 : public AbstractState
    {
    public:
    	ConcreteState1(Context * context) : AbstractState(context) { }
    	virtual void doSomething()
    	{
    		context()->switchToState(Context::State2);
    		context()->someCleanup();
    	}
    };
    
    class ConcreteState2 : public AbstractState
    {
    public:
    	ConcreteState2(Context * context) : AbstractState(context) { }
    	virtual void doSomething()
    	{
    		context()->switchToState(Context::State1);
    		context()->someCleanup();
    	}
    };
    
    void Context::switchToState(State newState)
    {
    	switch(newState)
    	{
    	case State1:
    		m_state.reset(new ConcreteState1(this));
    		return;
    	case State2:
    		m_state.reset(new ConcreteState2(this));
    		return;
    	}
    }

    Бывает, на меня находит состояние "сначала делай, потом думай", благо результат был быстро обнаружен отладчиком.

    Xom94ok, 10 Марта 2013

    Комментарии (1)