3

I have a lot of code in a big project that has two general types of code, some that is done in a nice C++ style and has been code reviewed by an expert in C++ and some that is not and has not. The code that is not has lots of for loops and unchecked array (heap) accesses consisting of both reads and writes. Fortunately, all these accesses to the heap are done through a class. For argument's sake, let's call it CArray.

CArray is defined entirely inside header files since it's templated. It is roughly defined as follows (only showing relevant portions):

template <typename elementType> class CArray
{
    /// Most of class details I'm leaving out

public:
    inline elementType & operator[](unsigned int i)
    {
#ifdef CARRAY_BOUNDARY_DEBUGGING
        if(i >= m_numElements)
        {
            throw SomeException("CArray::operator[] going out of bounds");
        }
#endif
        return m_pArray[i];
    }

    /// also have corresponding const version of this operator[]

private:
    elementType *m_pArray;
    int m_numElements;
}

(Please assume that the constructor, destructor, copy constructor, assignment operator and the corresponding rvalue reference versions are done right. Basically assume that the user of the class everything they need to use this class properly.

Now the question is, if I have some compilation units (.cpp files) that define CARRAY_BOUNDARY_DEBUGGING and then include this class (the ones needing code improvement/review), but others that do not (the ones that are rock solid):

  1. Is this guaranteed to be OK and not introduce problems since the class if often passed via copy, reference, and rvalue refrence (C++11 only) over compilation unit boundaries by C++03? C++11?

  2. Is there a better way to try to do this?

Edit: clarification. I know that non-inline functions must obey the one definition rule as stated in section 3.2 of the C++03 standard, but this is inline. Does the ODR still apply or is something else in effect here? Also the C++03 standard states "An inline function shall be defined in every translation unit in which it is used."

4

2 に答える 2

3

No, it's not okay, it's UB. Inlined definitions must be the same across the entire program. If you want to have additional logic used in some places, but not all, just make it another member (also writing CArray is silly):

struct silly_array {
    T& operator[](int x) { /* unchecked */ }
    T& at(int x) { /* check bounds */ return (*this)[x]; }
};
于 2012-05-20T12:56:35.920 に答える
2

You forgot to read the rest of the sentence you quoted. 7.1.2(4) "An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2)."

于 2012-05-20T14:30:51.487 に答える