cython icon indicating copy to clipboard operation
cython copied to clipboard

[BUG] type deduction ignores constness for stl square bracket operator and fails to compile

Open CypherGrue opened this issue 8 months ago • 1 comments

Describe the bug

When a type for a variable is not specified, it is deduced from the right hand side of an assignment. This deduction generally works except if the right hand side is a pointer to an element of a vector member of a const object, in which case the constness is lost. The error can be masked if another deduction for the same variable precedes the potentially erroneous one, as only the first deduction sets the type within a scope.

Code to reproduce the behaviour:

# distutils: language=c++

from libcpp.vector cimport vector

cdef struct S:
    vector[int] v
    int a

cdef void f1(const S &s):
    cref = &s.v[0]  # error: assigning to 'int *' from 'const value_type *' (aka 'const int *') discards

cdef void f2(const S &s):
    cref = &s.v[0]  # error: assigning to 'int *' from 'const value_type *' (aka 'const int *') discards
    cref = &s.a     # error: assigning to 'int *' from 'const int *' discards qualifiers

cdef void f3(const S &s):
    cref = &s.a     # OK
    cref = &s.v[0]  # OK

cdef S s
s.v.push_back(1)
f1(s)
f2(s)
f3(s)

Expected behaviour

No compile errors.

OS

Linux

Python version

3.12.3

Cython version

3.0.10

Additional context

C++ standard gives both options for square bracket access: reference operator[]( size_type pos ); const_reference operator[]( size_type pos ) const;

CypherGrue avatar Jun 25 '24 21:06 CypherGrue