Home > Backend Development > C++ > body text

Why Does Passing a Static Const Integer by Const Reference to a Template Function Cause an \'Undefined Reference\' Error?

Barbara Streisand
Release: 2024-11-04 08:46:30
Original
1004 people have browsed it

Why Does Passing a Static Const Integer by Const Reference to a Template Function Cause an

Undefined Reference to Static Const Int: Understanding the Compiler's Behavior

Consider a scenario where you define a template function foo that accepts a reference to a constant of type T. Within a class Bar, you declare a static constant integer kConst. When calling foo with kConst as an argument, the compiler may flag an "Undefined reference to 'Bar::kConst'" error.

This error arises because static const integers, while initialized at compile-time, still require a definition in the program if used in certain ways. According to the C standard (9.4.2/4), a const static data member can be initialized in its class definition if it's an integral constant expression. However, its declaration alone does not suffice for usage in const references or integral constant expressions.

When passing kConst by const reference to foo, you're effectively "using" it as per the standard (3.2/2). Since GCC considers the static data member to be "used," it demands its implementation in the program's scope. However, it allows leniency in the case of value-passing, where the lvalue-rvalue conversion occurs immediately.

Moreover, taking an address of or referencing non-existent objects is generally discouraged. Static data members reside in unique memory locations, and passing their addresses from multiple translation units may result in undefined behavior unless the object is explicitly defined in one TU.

In summary, the compiler error arises due to the requirement for a definition of static const integers if they're passed by const reference or used in constant expressions. It's imperative to adhere to the standard's guidelines to avoid such errors.

The above is the detailed content of Why Does Passing a Static Const Integer by Const Reference to a Template Function Cause an \'Undefined Reference\' Error?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!